package com.copro.chemdb.stat.rule;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;

import org.ihelpuoo.db.sql.SQLSegment;
import org.ihelpuoo.util.Properties;
import org.jfree.data.category.DefaultCategoryDataset;

import com.copro.chemdb.stat.AbstractStatRule;
import com.copro.chemdb.stat.StatResult;
import com.copro.chemdb.subject.Subject;
import com.copro.simple.Application;
import com.copro.simple.SimpleException;
import com.copro.simple.db.QueryCallback;
import com.copro.simple.db.QuickQueryCallback;

public class Rule8 extends AbstractStatRule {

	@Override
	public StatResult doStat(Application app, Subject subject, int type)
			throws SimpleException {
		SQLSegment sql = app.getSQL("rule8CountAnswer");
		sql.set("subjectId", subject.getId());
		sql.set("type", type);
		List<List<String>> industry = new LinkedList<List<String>>();
		QueryCallback callback = new QuickQueryCallback(industry) {
			@SuppressWarnings("unchecked")
			@Override
			public void exec(ResultSet rs) throws SQLException {
				while (rs.next()) {
					List<String> list = new ArrayList<String>(2);
					list.add(rs.getString(1));
					list.add(rs.getString(2));
					((List) obj).add(list);
				}
			}
		};
		app.query(sql.toString(), callback);

		sql = app.getSQL("rule8CountALL");
		sql.set("subjectId", subject.getId());
		sql.set("type", type);
		int count = app.getCount(sql.toString());

		Hashtable<String, Object> result = new Hashtable<String, Object>();

		result.put("industrySet", industry);
		result.put("count", String.valueOf(count));
		result.put("text", subject.getBrief());
		
		// start to create chart
		DefaultCategoryDataset dataset = new DefaultCategoryDataset();
		if (count > 0) {
			for (int si = 0; si < industry.size(); si++) {
				List<String> anIds = industry.get(si);
				dataset.setValue(Double.parseDouble(anIds.get(1)), anIds.get(0), "column1");
			}
		}
		app.createBarStatChart(subject.getId(), dataset);

		return new StatResult("rule8", result);
	}

	@Override
	public void setup(Properties conf) {
	}

}
